const express = require('express');
const router = express.Router();
const uuidv4 = require('uuid/v4');
const utils = require('../../utils');

const filters = [
    {
        Name: '名称',
        Type: 'String',
    },
    {
        Name: '详情',
        Type: 'String',
    },
];

// industry evaluation
router.get('/',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'industryeval'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } }
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '时间',
            '名称',
            '类型',
            '详情',

            'views',
            'applications',
            'downloads',
            'callbacks',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('industryeval', false, async (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.日期 = doc.时间 || doc.LastUpdateDate;
            doc.详情 = utils.repalceHtmlToText(doc.详情 || '');
            delete doc.LastUpdateDate;
            delete doc.时间;
        }
    })
);

// industry details
router.get('/:id',
    (req, res, next) => {
        res.locals.filter = { id: req.params.id, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } };
        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '推荐指数',
            '时间',
            
            '名称',
            '类型',
            '详情',
            '本地工具',
            'files',

            'views',
            'applications',
            'downloads',
            'callbacks',
        ];
        res.locals.options = {
            lean: true
        };

        return next();
    },
    router.FindDocuments('industryeval', false, async (req, res) => {
        if(res.locals.data && res.locals.data.total) {
            res.locals.data = res.locals.data.docs[0];

            res.locals.data.日期 = res.locals.data.时间 || res.locals.data.LastUpdateDate;
            delete res.locals.data.LastUpdateDate;
            delete res.locals.data.时间;

            if (req.user && req.user.id) {
                // 如果当前用户未分配工具调用key，
                let testKey = await res.app.models.test_keys.findOne({
                    User: req.user.id,
                    Tool: res.locals.data.id,
                });
    
                if (!testKey) {
                    testKey = await res.app.models.test_keys.create({
                        User: req.user.id,
                        Tool: res.locals.data.id,
                        Key: uuidv4(),
                    });
                }
    
                res.locals.data.K = testKey.Key;
            }

            // 更新查看次数
            await res.app.models['industryeval'].updateOne({ id: res.locals.data.id }, { $inc: { views: 1 } });
        } else {
            res.locals.data = {};
        }
    }),
);

// related
router.get('/related/:id',
    (req, res, next) => {
        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'industryeval'),
            { Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } },
            { id: {$ne: req.params.id }},
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            '时间',
            '日期',
            '名称',
            '类型',
            '详情',
        ];
        res.locals.options = {
            sort: { 推荐指数: 'desc', 时间: 'desc', LastUpdateDate: 'desc' },
            lean: true,
        };

        return next();
    },
    router.FindDocuments('industryeval', false, async (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.详情 = utils.repalceHtmlToText(doc.详情 || '');
            doc.日期 = doc.时间 || doc.日期 || doc.LastUpdateDate;
            delete doc.LastUpdateDate;
            delete doc.时间;
        }

        await utils.getDictLabel(req, res, '类型', '在线测评分类');
    })
);

router.post('/apply/:id', 
    async (req, res, next) => {
        // 必须登录才能申请服务
        if (!req.user || !req.user.id) {
            res.makeError(401, '登录后方可申请。');
            return next('route');
        }

        const sid = req.params.id;
        if (!sid) {
            res.makeError(400, '请选择检测。');
            return next('route');
        }

        const theEval = await res.app.models['industryeval'].findOne({ id: sid, Status: '1', Deleted: false, Freeze: { $exists: false, $ne: true } });
        if (!theEval) {
            res.makeError(403, '选择的检测不存在。');
            return next('route');
        }

        const appFlow = await res.app.models['flow'].findOne({ Code: 'evalapplication' });
        if (!appFlow) {
            await res.makeError(404, '此功能尚未启用！');
            return next();
        }

        const bodyKeys = Object.keys(req.body);

        const flowInfo = {
            Flow: appFlow.id,
            Steps: [null, {
                StartDate: new Date(),
                Status: '1'
            }, {
                StartDate: new Date(),
                Status: '0'
            }],
            Status: "0",
            CurrentStep: 2,
        };

        const doc = {
            检测: theEval.名称,
        };

        const fields = [
            '名称',
            '版本号',
            '来源',
            '附件',
            '单位',
            '联系人',
            '电话',
            '邮件',
            '描述',
        ];

        for (let i = 0; i < bodyKeys.length; i += 1) {
            const bk = bodyKeys[i];

            if (fields.indexOf(bk) >= 0) {
                doc[bk] = req.body[bk];
            }
        }

        // 更新申请次数
        await res.app.models['industryeval'].updateOne({ id: sid }, { $inc: { applications: 1 } });

        res.locals.body = {
            User: req.user.id,
            ...flowInfo,
            ...doc,
        };
        
        return next();
    },
    router.CreateDocument('evalapplication'),
);

router.get(
  '/tests',
  (req, res, next) => {
    res.locals.filter = {
      User: req.user.id,
      Deleted: false,
      Freeze: { $exists: false, $ne: true },
    };

    res.locals.fields = [
        'id',
        'LastUpdateDate',
        'Status',
        '单位',
        '名称',
        '描述',
        '来源',
        '检测',
        '版本号',
        '电话',
        '联系人',
        '邮件',
        '附件',
        '处理意见',
    ];

    res.locals.options = {
      sort: { 推荐指数: "desc", 时间: "desc", LastUpdateDate: "desc" },
      lean: true,
    };

    return next();
  },
  router.FindDocuments('evalapplication', false, async (req, res) => {
    const docs = res.locals.data.docs;

    for (let i = 0 ; i < docs.length; i += 1) {
        const doc = docs[i];

        // modify for return
        docs[i] = {
            ... doc,
            StatusLabel: router.mdl.t(
                `evalStatus${doc.Status}`, 
                // req.query.locale
            ) || '',
        }

        delete doc.tid;
    }
  })
);

module.exports = router;
